﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO.MemoryMappedFiles;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace MemoryMappedFileS
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        private const int FILE_SIZE = 512;
        private void Form1_Load(object sender, EventArgs e)
        {




            ShowContent();
        }

        private void ShowContent()
        {
            using (MemoryMappedFile mpfFile = MemoryMappedFile.OpenExisting("SwapFile",
                MemoryMappedFileRights.FullControl, System.IO.HandleInheritability.Inheritable))
            {
                MemoryMappedViewAccessor accessor = mpfFile.CreateViewAccessor();
                StringBuilder sb = new StringBuilder(FILE_SIZE);
                sb.Append("上半段内容：\n");

                int j = 0;
                for (int i = 0; i < FILE_SIZE / 2; i += 2)
                {
                    sb.Append("\t");
                    char ch = accessor.ReadChar(i);
                    sb.Append(j);
                    sb.Append(":");
                    sb.Append(ch);
                    j++;
                }
                sb.Append("\n下半段内容：\n");

                for (int i = FILE_SIZE / 2; i < FILE_SIZE; i += 2)
                {
                    sb.Append("\t");
                    char ch = accessor.ReadChar(i);
                    sb.Append(j);
                    sb.Append(":");
                    sb.Append(ch);
                    j++;
                }
                accessor.Dispose();
                richTextBoxFile.Text = sb.ToString();
            }
        }

        private void btnAppend_Click(object sender, EventArgs e)
        {

            if (string.IsNullOrEmpty(textBoxAppend.Text))
            {

                return;
            }

            char[] chs = textBoxAppend.Text.ToCharArray();
            char ch = chs[0];


            using (MemoryMappedFile mpfFile = MemoryMappedFile.OpenExisting("SwapFile",
                MemoryMappedFileRights.FullControl, System.IO.HandleInheritability.Inheritable))
            {


                MemoryMappedViewAccessor accessor = mpfFile.CreateViewAccessor();
                for (int i = 0; i < FILE_SIZE / 2; i += 2)
                {
                    accessor.Write(i, ch);
                }

                accessor.Dispose();
            }

            ShowContent();
        }

        private void btnLoad_Click(object sender, EventArgs e)
        {
            ShowContent();
        }
    }
}
